package com.luckberry.murder.controller.auth;

import com.luckberry.murder.entity.User;
import com.luckberry.murder.entity.VIP;
import com.luckberry.murder.service.UserService;
import com.luckberry.murder.service.VIPService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping("/auth")
public class AuthController {

    public static final HashMap<Integer, User> onlines = new HashMap<>();
    @Resource
    private UserService userService;
    @Resource
    private VIPService vipService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpSession session, String account, String password) {
        if (!userService.login(session, account, password)) {
            session.setAttribute("login_fail", true);
            return "redirect:/login";
        }
        User user = (User) session.getAttribute("user");
        if (!user.getPerm().equals("admin")) onlines.put(user.getUid(), user);
        // VIP过期
        VIP vip = vipService.getVIP(user.getUid());
        if (vip != null && vip.getTime().getTime() + (long) vip.getMonth() * 30 * 24 * 60 * 60 * 1000 < new Date().getTime()) {
            vipService.deleteVIP(user.getUid());
            user.setPerm("user");
            userService.editUser(user);
            session.setAttribute("user", userService.getUser(user.getUid()));
        }
        return "redirect:/index";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        onlines.remove(((User) session.getAttribute("user")).getUid());
        session.removeAttribute("user");
        return "redirect:/login";
    }

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String signup(String name, String account, String password, String perm) {
        if (perm == null || perm.equals("")) perm = "user";
        User user = User.builder()
                .name(name)
                .account(account)
                .password(password)
                .perm(perm)
                .face("/assets/images/user.png")
                .build();
        if (userService.addUser(user)) return "redirect:/login";
        return "redirect:/signup";
    }
}
